package com.example.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.example.R;
import com.example.model.EventBean;
import com.example.util.Constant;
import com.example.widget.X5WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的Fragment
 */
public class MineFragment extends Fragment {
    @BindView(R.id.web_view_mine)
    X5WebView webView;

    private View rootView;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private String loadUrl = Constant.H5_URL + "my";
    private Uri imageUri;
    private int REQUEST_CODE = 0x15;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView==null){
            rootView =inflater.inflate(R.layout.fragment_mine,null,false);
            ButterKnife.bind(this,rootView);
            EventBus.getDefault().register(this);

        }
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initWebView();
        registerForContextMenu(webView);
    }

    /**
     *
     */
    private void initWebView(){
        webView.getSettings().setUseWideViewPort(true);
        webView.loadUrl(loadUrl);

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                webView.evaluateJavascript("document.getElementsByTagName('body')[0].getElementsByClassName('kz-float-layer bottom')[0].remove();",
                        new ValueCallback<String>() {
                            //加载网页结束之后的
                            @Override
                            public void onReceiveValue(String s) {
                                Log.e("zz", s);
                            }
                        });
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            //加载进度
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                Log.e("zz", String.valueOf(i));
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
                uploadFiles = valueCallback;
                takePhoto();
                return true;
            }
        });

    }



    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBean bean) {
        webView.loadUrl(loadUrl);
        webView.loadUrl( "javascript:window.location.reload( true )" );
    }

    /**
     *
     */
    private void takePhoto() {
        String filePath = Environment.getExternalStorageDirectory() + File.separator
                + Environment.DIRECTORY_PICTURES + File.separator;
        String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        imageUri = Uri.fromFile(new File(filePath + fileName));

        Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        Intent Photo = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        Intent chooserIntent = Intent.createChooser(Photo, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, REQUEST_CODE);
    }

    /**
     *
     * @param resultCode
     * @param data
     */
    private void chooseAbove(int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            updatePhotos();
            if (data != null) {
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                        //Log.e("--MineFragment", "系统返回URI：" + uri.toString());
                    }
                    uploadFiles.onReceiveValue(results);
                } else {
                    uploadFiles.onReceiveValue(null);
                }
            } else {
                uploadFiles.onReceiveValue(new Uri[]{imageUri});
            }
        } else {
            uploadFiles.onReceiveValue(null);
        }
        uploadFiles = null;
    }

    /**
     *
     */
    private void updatePhotos() {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        getActivity().sendBroadcast(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (uploadFiles != null) {
                chooseAbove(resultCode, data);
            } else {
                Toast.makeText(getActivity(), "发生错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(webView!=null){
            webView.destroy();
        }
        EventBus.getDefault().unregister(this);
    }
}
